<?php

namespace app\admin\controller\qingdongwms\customer;

use addons\qingdongwms\model\ContactsFile;
use addons\qingdongwms\model\ReceivablesPlan;
use app\admin\controller\qingdongwms\Base;
use addons\qingdongwms\model\Staff;
use think\Db;
use think\Exception;
use addons\qingdongwms\model\Customer;
use addons\qingdongwms\model\Contacts;
use addons\qingdongwms\model\Form;
use addons\qingdongwms\model\CustomerOther;
use addons\qingdongwms\model\Receivables;
use addons\qingdongwms\model\Record;
use addons\qingdongwms\model\Contract;
use addons\qingdongwms\model\Comment;
use addons\qingdongwms\model\Consume;
/**
 * 客户查重管理
 * @desc 操作文档：https://doc.fastadmin.net/qingdongwms
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongwms.html
 * @desc 售后微信：qingdong_crm
 */
class Cnki extends Base
{
    protected $relationSearch = true;
    /**
     * @var \addons\qingdongwms\model\Customer
     */
    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \addons\qingdongwms\model\Customer;
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $customer_ids_name=Customer::where('name in '.Customer::where([])->having('count(*) > 1')->group('name')->field('name')->buildSql(true))->column('id');
            $customer_ids_mobile= Contacts::where('mobile in '. Contacts::where([])->having('count(*) > 1')->group('mobile')->where(['mobile'=>['neq','']])->field('mobile')->buildSql(true))->column('customer_id');
            $customer_ids_email = Contacts::where('email in '.Contacts::where([])->having('count(*) > 1')->group('email,customer_id')->where(['email'=>['neq','']])->field('email')->buildSql(true))->column('customer_id');
            $customer_ids=array_merge($customer_ids_name?:[],$customer_ids_mobile?:[],$customer_ids_email?:[]);
            $customer_ids=array_values(array_unique($customer_ids));
            $list = $this->model->where($where)
                ->where(['id'=>['in',$customer_ids]])
                ->order($sort, $order)->paginate($limit);
            $rows = $list->items();
            foreach($rows as $k=>$v){
                $contacts = Contacts::where(array('customer_id'=>$v['id']))->select();
                foreach($contacts as $ks=>$vs){
                    $emailinfo='';
                    $mobileinfo ='';
                    if($vs['mobile']){
                        $mobileinfo = Contacts::where(array('id'=>['neq',$vs['id']],'customer_id'=>$v['id'],'mobile'=>$vs['mobile']))->value('id');
                    }
                    if($vs['email']){
                        $emailinfo = Contacts::where(array('id'=>['neq',$vs['id']],'customer_id'=>$v['id'],'email'=>$vs['email']))->value('id');
                    }
                    if($mobileinfo || $emailinfo){
                            unset($rows[$k]);
                    }
                }

            }
            $result = array("total" => $list->total(), "rows" => array_values($rows));

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 合并客户
     */
    public function edit($ids=null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $check = isset($params['check']) ? $params['check'] : '';
                $ids = $params['id'];
                $customer_ids = $params['customer_ids'];
                unset($params['check']);
                unset($params['customer_ids']);
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $params['id'] = $ids;
                    $result = $this->model::updateCustomer($params);
                    //合并后删除被合并客户
                    $rescustomer = true;
                    $rescontacts = true;
                    $resrecord = true;
                    $rescontract = true;
                    $resconsume = true;
                    $resreceivables = true;
                    $resreceivables_plan = true;
                    $rescomment = true;
                    if($check == 1){
                        //客户
                        $hecustomer = $this->model->where(array('id'=>$customer_ids))->find();
                        if($hecustomer){
                            $rescustomer = $this->model->where(array('id'=>$customer_ids))->update(array('deletetime'=>time()));
                        }
                        //联系人
                        $hecontacts =Contacts::where(array('customer_id'=>$customer_ids))->find();
                        if($hecontacts){
                            $rescontacts = Contacts::where(array('customer_id'=>$customer_ids))->update(array('customer_id'=>$ids,'updatetime'=>time()));
                        }
                        //跟进记录
                        $herecord = Record::where(array('relation_type'=>1,'relation_id'=>$customer_ids))->find();
                        if($herecord){
                            $resrecord = Record::where(array('relation_type'=>1,'relation_id'=>$customer_ids))->update(array('relation_id'=>$ids,'updatetime'=>time()));
                        }
                        //合同
                        $hecontract=Contract::where(array('customer_id'=>$customer_ids))->find();
                        if($hecontract){
                            $rescontract=Contract::where(array('customer_id'=>$customer_ids))->update(array('customer_id'=>$ids,'updatetime'=>time()));
                        }
                        //费用
                        $heconsume = Consume::where(array('customer_id'=>$customer_ids))->find();
                        if($heconsume){
                            $resconsume = Consume::where(array('customer_id'=>$customer_ids))->update(array('customer_id'=>$ids,'updatetime'=>time()));
                        }
                        //回款
                        $hereceivables = Receivables::where(array('customer_id'=>$customer_ids))->find();
                        if($hereceivables){
                            $resreceivables = Receivables::where(array('customer_id'=>$customer_ids))->update(array('customer_id'=>$ids,'updatetime'=>time()));
                        }
                        //回款计划
                        $hereceivables_plan = ReceivablesPlan::where(array('customer_id'=>$customer_ids))->find();
                        if($hereceivables_plan){
                            $resreceivables_plan = ReceivablesPlan::where(array('customer_id'=>$customer_ids))->update(array('customer_id'=>$ids,'updatetime'=>time()));
                        }
                        //评论
                        $hecomment = Comment::where(array('relation_type'=>1,'relation_id'=>$customer_ids))->find();
                        if($hecomment){
                            $rescomment = Comment::where(array('relation_type'=>1,'relation_id'=>$customer_ids))->update(array('relation_id'=>$ids,'updatetime'=>time()));

                        }
                        if(!$rescustomer || !$rescontacts || !$resrecord  || !$rescontract || !$resconsume || !$resreceivables || !$resreceivables_plan || !$rescomment){
                            $result = false;
                            throw new Exception('合并失败');
                        }
                    }else{
                        //联系人
                        $hecontacts = collection(Contacts::where(array('customer_id'=>$customer_ids))->select())->toArray();
                        foreach($hecontacts as $k=>$v){
                            unset($v['id']);
                            $mobileinfo = Contacts::where(array('customer_id'=>$customer_ids,'mobile'=>$v['mobile']))->value('id');
                            $emailinfo = Contacts::where(array('customer_id'=>$customer_ids,'email'=>$v['email']))->value('id');
                            if($emailinfo){
                                $v['email'] = '';
                            }
                            if(($mobileinfo && $emailinfo) || $mobileinfo){
                                continue;
                            }
                            $v['customer_id'] = $ids;
                            $rescontacts = Contacts::create($v);
                        }

                        //跟进记录
                        $herecords = collection(Record::where(array('relation_type'=>1,'relation_id'=>$customer_ids))->select())->toArray();
                        foreach($herecords as $k=>$vs){
                            unset($vs['id']);
                            $vs['relation_id'] = $ids;
                            $resrecord = Record::create($vs);
                        }
                        //合同
                        $hecontract=collection(Contract::where(array('customer_id'=>$customer_ids))->select())->toArray();
                        foreach($hecontract as $k=>$v){
                            unset($v['id']);
                            $v['customer_id'] = $ids;
                            $rescontract = Contract::create($v);
                        }
                        //费用
                        $heconsume = collection(Consume::where(array('customer_id'=>$customer_ids))->select())->toArray();
                        foreach($heconsume as $k=>$v){
                            unset($v['id']);
                            $v['customer_id'] = $ids;
                            $resconsume = Consume::create($v);
                        }
                        //回款
                        $hereceivables = collection(Receivables::where(array('customer_id'=>$customer_ids))->select())->toArray();
                        foreach($hereceivables as $k=>$v){
                            unset($v['id']);
                            $v['customer_id'] = $ids;
                            $resreceivables = Receivables::create($v);
                        }
                        //回款计划
                        $hereceivables_plan = collection(ReceivablesPlan::where(array('customer_id'=>$customer_ids))->select())->toArray();
                        foreach($hereceivables_plan as $k=>$v){
                            unset($v['id']);
                            $v['customer_id'] = $ids;
                            $resreceivables_plan = ReceivablesPlan::create($v);
                        }
                        //评论
                        $hecomment = collection(Comment::where(array('relation_type'=>1,'relation_id'=>$customer_ids))->select())->toArray();
                        foreach($hecomment as $k=>$v){
                            unset($v['id']);
                            $v['relation_id'] = $ids;
                            $rescomment = Comment::create($v);
                        }

                        if(!$rescontacts || !$resrecord  || !$rescontract || !$resconsume || !$resreceivables || !$resreceivables_plan || !$rescomment){
                            $result = false;
                            throw new Exception('合并失败');
                        }
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error('合并失败');
                }
            }
            $this->error('参数不能为空');
        }
        //客户
        $row = Customer::where(array('id'=>$ids))->find();
        if(!$row){
            $this->error('客户不存在');
        }
        $row=$row->toArray();
        $row = CustomerOther::getOther($row);
        $fieldlist = Form::getDataValue('customer');

        //被合并客户信息
        $customer_ids = Customer::where(array('name'=>$row['name'],'id'=>['neq',$ids]))->value('id');
        if(!$customer_ids){
            //手机号
            $wheres['customer_id'] = array('neq',$ids);
            $customer_ids_mobile = Contacts::where(array('customer_id'=>$ids))->field('mobile')->group('mobile')->column('mobile');
            if($customer_ids_mobile){
                $customer_ids_mobile = Contacts::where($wheres)->where('mobile', 'in', $customer_ids_mobile)->value('customer_id');
                if($customer_ids_mobile){
                    $customer_ids = $customer_ids_mobile;
                }
            }
            $customer_ids_email = Contacts::where(array('customer_id'=>$ids))->field('email')->group('email')->column('email');
            if($customer_ids_email){
                $customer_ids_email = Contacts::where($wheres)->where('email', 'in', $customer_ids_mobile)->value('customer_id');
                if($customer_ids_email){
                    $customer_ids = $customer_ids_email;
                }
            }
        }
        if(!$customer_ids){
            $this->error('被合并客户不存在');
        }
        $rowinfo = Customer::where(array('id'=>$customer_ids))->find();
        $rowinfo=$rowinfo->toArray();
        $rowinfo = CustomerOther::getOther($rowinfo);
        $hecustomer = $fieldlist;
        $hecustomerInfo = [];
        foreach($hecustomer as $k=>$v){
            $hecustomerInfo[$v['id']] = $v;
            $hecustomerInfo[$v['id']]['value']= $rowinfo[$v['id']]??'';

        }

        $zucustomer = $fieldlist;
        //主客户信息
        foreach($zucustomer as $k=>$v){
            $zucustomer[$k]['value']= $row[$v['id']]??'';

            if(key_exists($v['id'],$hecustomerInfo)){
                $zucustomer[$k]['chilend'] = $hecustomerInfo[$v['id']];;
            }
        }

        $check = array('1'=>'合并后删除被合并客户');
        $this->assign('check',$check);
        $this->assign('form_data', $zucustomer);
        $this->assign('ids',$ids);
        $this->assign('customer_ids',$customer_ids);
        return $this->view->fetch();
    }

}
